﻿using System.Collections.Generic;
using NAGFwk.UI;
using SilkeyERP.BL;
using SilkeyERP.Model;
using System.Threading.Tasks;
using System.Linq;

namespace SilkeyERP.UI.Entities.SalesPerson
{
    public partial class CustomEditContentView : BaseCustomEditForm
    {
        private Model.SalesPerson current { get; set; }

        public CustomEditContentView()
        {
            InitializeComponent();
            SetInitialDataSource();
            btnCustomerSearch.FormChooserType = new Shared.CustomerChooser();
            btnCustomerSearch.OnSelected += btnCustomerSearch_OnSelected;
            btnSalesPriceListSearch.FormChooserType = new Shared.SalesPriceListChooser();
            btnSalesPriceListSearch.OnSelected += btnSalesPriceListSearch_OnSelected;
            createDateDateEdit.Enabled = false;
            modificationDateDateEdit.Enabled = false;
            streetTextEdit.Enabled = false;
            xtcSalesPersonDetail.SelectedTabPageIndex = 0;          
        }

        void btnSalesPriceListSearch_OnSelected(List<dynamic> SelectedItems)
        {
            foreach (var SelectedItem in SelectedItems)
                if (!salesPriceListBindingSource.Contains(SelectedItem))
                    salesPriceListBindingSource.Add(SelectedItem);
        }

        void btnCustomerSearch_OnSelected(List<dynamic> SelectedItems)
        {
            if (SelectedItems.Count > 0)
            {
                if (SelectedItems.ConvertAll(x => (Model.Customer)x).FindAll(x => x.SalesPerson.SalesPersonID != this.current.SalesPersonID).Count > 0)
                    if (System.Windows.Forms.MessageBox.Show(Properties.Resources.SalesPersonAssociatedClientFromAnotherSalesPerson, Properties.Resources.GeneralMessageTitleWarning, System.Windows.Forms.MessageBoxButtons.OKCancel) != System.Windows.Forms.DialogResult.OK)
                        btnCustomerSearch.ShowChooserForm();
            }
            foreach (var SelectedItem in SelectedItems)
                if (!customerAssociatedBindingSource.Contains(SelectedItem))
                    customerAssociatedBindingSource.Add(SelectedItem);
        }

        private void SetInitialDataSource()
        {
            cityBindingSource.DataSource = new CityController().GetAll();
            provinceBindingSource.DataSource = new ProvinceController().GetAll();
            customerBindingSource.DataSource = new CustomerController().GetAll();
            taxBindingSource.DataSource = new TaxController().GetAll();
            taxFigureBindingSource.DataSource = new TaxFigureController().GetAll();
            salesStatusBindingSource.DataSource = new SalesStatusController().GetAll();
            customerTypeBindingSource.DataSource = new CustomerTypeController().GetAll();
            buyPriceListBindingSource.DataSource = new BuyPriceListController().GetAll();
        }

        public void InitData(ref Model.SalesPerson currentSalesPerson)
        {
            var _currentSalesPersonPhones = new List<Model.Phones>();
            var _oriSalesPersonPhones = currentSalesPerson.Phones.Where(x => x.Enable);
            if (_oriSalesPersonPhones.Count() != 0)
                _currentSalesPersonPhones.AddRange(_oriSalesPersonPhones.ToList());
            phonesBindingSource.DataSource = _currentSalesPersonPhones;
            currentSalesPerson.Phones = _currentSalesPersonPhones;

            var _currentSalesPersonEmail = new List<Model.Email>();
            var _oriSalesPersonEmail = currentSalesPerson.Email.Where(x => x.Enable);
            if (_oriSalesPersonEmail.Count() != 0)
                _currentSalesPersonEmail.AddRange(_oriSalesPersonEmail.ToList());
            emailBindingSource.DataSource = _currentSalesPersonEmail;
            currentSalesPerson.Email = _currentSalesPersonEmail;

            var _currentSalesPersonAddress = new List<Model.Address>();
            var _oriSalesPersonAddress = currentSalesPerson.Address.Where(x => x.Enable);
            if (_oriSalesPersonAddress.Count() != 0)
                _currentSalesPersonAddress.AddRange(_oriSalesPersonAddress.ToList());
            addressBindingSource.DataSource = _currentSalesPersonAddress;
            currentSalesPerson.Address = _currentSalesPersonAddress;

            var _currentSalesPersonCustomer = new List<Model.Customer>();
            var _oriSalesPersonCustomer = currentSalesPerson.Customer.Where(x => x.Enable);
            if (_oriSalesPersonCustomer.Count() != 0)
                _currentSalesPersonCustomer.AddRange(_oriSalesPersonCustomer.ToList());
            customerAssociatedBindingSource.DataSource = _currentSalesPersonCustomer;
            currentSalesPerson.Customer = _currentSalesPersonCustomer;

            var _currentSalesPersonSalesPriceList = new List<Model.SalesPriceList>();
            var _oriSalesPersonSalesPriceList = currentSalesPerson.SalesPriceList.Where(x => x.Enable);
            if (_oriSalesPersonSalesPriceList.Count() != 0)
                _currentSalesPersonSalesPriceList.AddRange(_oriSalesPersonSalesPriceList.ToList());
            salesPriceListBindingSource.DataSource = _currentSalesPersonSalesPriceList;
            currentSalesPerson.SalesPriceList = _currentSalesPersonSalesPriceList;

            salesBindingSource.DataSource = currentSalesPerson.Sales;          

            current = currentSalesPerson;

            if (IsNew)
                current.SetNextAvailableSalesPerson();

            if (IsEdit)
            {
                salesPersonCodeSpinEdit.Enabled = false;
                if (current.Address.Count > 0)
                {
                    var currentDefaultAddress = current.Address.Single(x => x.Order == 0);
                    streetTextEdit.Text = streetTextEdit.Text = string.Format("{0}: {1} {2}", currentDefaultAddress.Description, currentDefaultAddress.Street, currentDefaultAddress.Number);
                }
                else
                    streetTextEdit.Text = string.Empty;
            }
        }

        private void addressGridView_ValidateRow(object sender, DevExpress.XtraGrid.Views.Base.ValidateRowEventArgs e)
        {
            if (e.Row.GetType() == typeof(Model.Address))
            {
                var typedRow = (Model.Address)e.Row;

                if (string.IsNullOrEmpty(typedRow.Description))
                {
                    e.ErrorText = Properties.Resources.ErrorAddressDescriptionRequired;
                    e.Valid = false;
                }
                if (string.IsNullOrEmpty(typedRow.Street))
                {
                    e.ErrorText = Properties.Resources.ErrorAddressStreetRequired;
                    e.Valid = false;
                }

                if (string.IsNullOrEmpty(typedRow.Number.ToString()))
                {
                    e.ErrorText = "Numero en Direccion es requerido.";
                    e.Valid = false;
                }

                if (new AddressController().GetAll().Exists(x => x.Order == typedRow.Order && x.SalesPerson.Any(y => y.SalesPersonID == current.SalesPersonID)))
                {
                    e.ErrorText = string.Format("Ya existe una direccion con el orden {0}", typedRow.Order);
                    e.Valid = false;
                }
            }
            else if (e.Row.GetType() == typeof(Model.Email))
            {
                var typedRow = (Model.Email)e.Row;

                if (string.IsNullOrEmpty(typedRow.Description))
                {
                    e.ErrorText = Properties.Resources.ErrorEmailDescriptionRequired;
                    e.Valid = false;
                }
                if (string.IsNullOrEmpty(typedRow.Email1))
                {
                    e.ErrorText = Properties.Resources.ErrorEmailRequired;
                    e.Valid = false;
                }

                if (new EmailController().GetAll().Exists(x => x.Order == typedRow.Order && x.SalesPerson.Any(y => y.SalesPersonID == current.SalesPersonID)))
                {
                    e.ErrorText = string.Format("Ya existe un Email con el orden {0}", typedRow.Order);
                    e.Valid = false;
                }
            }
            else if (e.Row.GetType() == typeof(Model.Phones))
            {
                var typedRow = (Model.Phones)e.Row;

                if (string.IsNullOrEmpty(typedRow.Description))
                {
                    e.ErrorText = Properties.Resources.ErrorPhonesDescriptionRequired;
                    e.Valid = false;
                }
                if (string.IsNullOrEmpty(typedRow.Number.ToString()))
                {
                    e.ErrorText = Properties.Resources.ErrorPhoneNumberRequired;
                    e.Valid = false;
                }

                if (new PhonesController().GetAll().Exists(x => x.Order == typedRow.Order && x.SalesPerson.Any(y => y.SalesPersonID == current.SalesPersonID)))
                {
                    e.ErrorText = string.Format("Ya existe un Telefono con el orden {0}", typedRow.Order);
                    e.Valid = false;
                }

            }
        }

    }
}
